/**
 * 通过 tests 目录下的 .test.ts 生成说明文档
 */
const fs = require('fs');
const path = require('path');
const srcPath = path.resolve(__dirname, '../tests/modules');
const mdPath = path.resolve(__dirname, '../README.md');
const comMdPath = path.resolve(__dirname, './comReademe.md');

function sleep(t) {
    return new Promise(a => setTimeout(a, t))
}
// 解析文件
async function parseFile(ctx) {
    let title = ''
    ctx.replace(/【([\s\S]+?)】/, (all, item) => {
        title = item
    })
    let fnNameList = []
    ctx.replace(/describe[\s\S\n]+?\}\)[\r\n]/g, (all) => {
        fnNameList.push(all)
    })
    await sleep(10)
    return { title, fnNameList }
}
// 读取所有文件
async function getFileDocList() {
    var result = []
    const fileList = fs.readdirSync(srcPath)
    for (let fileName of fileList) {
        let content = fs.readFileSync(path.join(srcPath, fileName))
        let res = await parseFile(content.toString())
        result.push(res)
    }
    return result
}
// 解析每个方法的代码
function getCode(list) {
    let fileStr = ''
    for (let itemFn of list) {
        let title = ''
        let content = ''
        itemFn.replace(/describe\('([\S\s]+?)'/, (all, t) => {
            title = t
        })
        content = itemFn.replace(/^[\s\S]+?\n/, '\n').replace(/\}\)[\r\n]$/, '')
        content = content.replace(/\n\s\s\s\s/g, '')
        fileStr += `\n## ${title}\n` + '```js\n' + content + '\n```'
    }
    return fileStr
}
// 写入 md 文件
async function createMd() {
    var codeContent = ''
    let docList = await getFileDocList()
    for (let item of docList) {
        if (!item.fnNameList.length) {
            console.info(item, '未获取到方法')
            return
        }
        codeContent += `\n# ${item.title}\n${getCode(item.fnNameList)}`
    }
    let comReademe = fs.readFileSync(comMdPath).toString()
    let mdstr = comReademe.replace(/\{codeContent\}/, codeContent)
    fs.writeFileSync(mdPath, mdstr)
    console.log('[ readme.md 写入完成 ]')
}

createMd()